package com.imooc.ecommerce.feign;

import feign.RequestInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * Feign 调用时, 把 Header也传递到服务提供方
 *
 * @author zhangshao
 * @since 2023/12/13 23:20
 */
@Slf4j
@Configuration
public class FeignConfig {

    /**
     * 给feign 配置请求拦截器
     * RequestInterceptor 是提供给openFeign的请求拦截器, 把header向下传递
     */
    @Bean
    public RequestInterceptor headerInterceptor() {
        return template -> {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

            if (null != attributes) {
                HttpServletRequest request = attributes.getRequest();
                Enumeration<String> headerNames = request.getHeaderNames();
                if (null != headerNames) {
                    while (headerNames.hasMoreElements()) {
                        String name = headerNames.nextElement();
                        String values = request.getHeader(name);
                        //不能把当前请求的content-length传递到下游的服务提供方,这明显是不对的
                        // 请求可能一直返回不了,或者是请求响应数据被截断
                        if (!name.equalsIgnoreCase("content-length")) {
                            // 这里的 template 就是RestTemplate
                            template.header(name, values);
                        }
                    }
                }
            }
        };

    }

}
